/**
 * token操作封装
 */
import { MCH_CACHE_ID, TOKEN_CACHE_NAME } from '@/config/setting'

/**
 * 获取缓存的token
 */
export function getToken() {
  const token = localStorage.getItem(TOKEN_CACHE_NAME)
  if (!token) {
    return sessionStorage.getItem(TOKEN_CACHE_NAME)
  }
  return token
}

/**
 * 缓存token
 * @param token token
 * @param remember 是否永久存储
 */
export function setToken(token, remember) {
  removeToken()
  if (token) {
    if (remember) {
      localStorage.setItem(TOKEN_CACHE_NAME, token)
    }
    else {
      sessionStorage.setItem(TOKEN_CACHE_NAME, token)
    }
  }
}

/**
 * 移除token
 */
export function removeToken() {
  localStorage.removeItem(TOKEN_CACHE_NAME)
  sessionStorage.removeItem(TOKEN_CACHE_NAME)
  removeMchId()
}

/**
 * 获取缓存的token
 */
export function getMchId() {
  const mchId = localStorage.getItem(MCH_CACHE_ID)
  if (!mchId) {
    return sessionStorage.getItem(MCH_CACHE_ID)
  }
  return mchId
}

/**
 * 缓存token
 * @param token token
 * @param remember 是否永久存储
 */
export function setMchId(mchId, remember = true) {
  removeMchId()
  if (mchId) {
    if (remember) {
      localStorage.setItem(MCH_CACHE_ID, mchId)
    }
    else {
      sessionStorage.setItem(MCH_CACHE_ID, mchId)
    }
  }
}

/**
 * 移除token
 */
export function removeMchId() {
  localStorage.removeItem(MCH_CACHE_ID)
  sessionStorage.removeItem(MCH_CACHE_ID)
}
